﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Celeriq.Common;
using Celeriq.Graphing.Core;

namespace Celeriq.ManagementStudio
{
	public partial class ServerInfoForm : Form
	{
		private string _serverName;
		private UserCredentials _credentials;
		private string _publicKey;

		public ServerInfoForm()
		{
			InitializeComponent();
		}

		public ServerInfoForm(string serverName, UserCredentials credentials, string publicKey)
			: this()
		{
			_serverName = serverName;
			_credentials = credentials;
			_publicKey = publicKey;

			txtPublicKey.Text = publicKey;
			txtName.Text = serverName;

			try
			{
				using (var factory = SystemCoreInteractDomain.GetFactory(serverName))
				{
					var server = factory.CreateChannel();
					var settings = server.GetServerResourceSetting(credentials);
					udLoaded.Value = settings.MaxRunningRepositories;
					udMemory.Value = settings.MaxMemory / (1024 * 1024);
					udTime.Value = settings.AutoDataUnloadTime;
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show("An error occurred connecting to server.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
				this.Close();
				return;
			}

		}

		private void cmdClose_Click(object sender, EventArgs e)
		{
			this.Close();
		}

		private void cmdUsers_Click(object sender, EventArgs e)
		{
			var F = new UserListForm();
			F.ShowDialog();
		}

		private void cmdOK_Click(object sender, EventArgs e)
		{
			try
			{
				using (var factory = SystemCoreInteractDomain.GetFactory(_serverName))
				{
					var server = factory.CreateChannel();
					var settings = server.GetServerResourceSetting(_credentials);
					settings.MaxRunningRepositories = (int)udLoaded.Value;
					settings.MaxMemory = (int)udMemory.Value*(1024*1024);
					settings.AutoDataUnloadTime = (int)udTime.Value;
					server.SaveServerResourceSetting(_credentials, settings);
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show("An error occurred connecting to server.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
				this.Close();
				return;
			}

			this.Close();

		}
	}
}
